package wangwenjun.phase1.ticketwindow;

import lombok.extern.slf4j.Slf4j;
import util.ThreadUtil;

import java.util.*;

/**
 * @author ChangLiang
 * @date 2020/5/29
 */
@Slf4j
public class TicketWindowV4Runnable implements Runnable {

    private static int index = 1;

    private final static int MAX = 50;

    /**
     * 这是一个线程安全的set
     */
    private static Set<Integer> set = Collections.synchronizedSet(new LinkedHashSet<>());

    private static List<Integer> list = Collections.synchronizedList(new ArrayList<>());

    public int getListSize() {
        System.out.println(Arrays.toString(list.toArray()));
        return list.size();
    }

    public int getSetSize() {
        System.out.println(Arrays.toString(set.toArray()));
        return set.size();
    }

    @Override
    public void run() {
        // 注意while和synchronized顺序 这个顺序会导致51出现
        while (index <= MAX) {
            synchronized (TicketWindowV4Runnable.class) {
                set.add(index);
                list.add(index);
                log.info("{}的号码是: {}", Thread.currentThread(),index++);
            }
            ThreadUtil.sleepForMilliSeconds(100);
        }
    }
}
